package com.example.l2p_feedback;

import org.json.JSONObject;

import android.app.Activity;
import android.content.Context;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;

public class View02_CourseSuggestion extends Activity {
	TextView tView, cView;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.view02_new_suggestion);

		this.setTitle("New suggestion");
		tView = (TextView) findViewById(R.id.view0203_entry);
		cView = (TextView) findViewById(R.id.view0203_content);

		tView.setText("L2P-Feedback-App-Suggestions");

		Button button = (Button) findViewById(R.id.view0203_button_submit);
		button.setOnClickListener(new View.OnClickListener() {
			public void onClick(View v) {
				Context context = View02_CourseSuggestion.this;
				SharedPreferences settings = PreferenceManager
						.getDefaultSharedPreferences(context);
				String token = settings.getString("token", "");
				SharedPreferences.Editor editor = settings.edit();
				//editor.putString("wikiID","").commit();
				try {
					String wikiID = settings.getString("wikiID", ""), msg;
					if (wikiID != "" && Integer.parseInt(wikiID) >= 0) {
						String url = "https://www.elearning.rwth-aachen.de/_vti_bin/l2pservices/api.svc/v1/updateWiki?accessToken="
								+ token
								+ "&cid=14ss-38343&title="
								+ tView.getText().toString()
								+ "&body="
								+ cView.getText().toString()
								+ "&itemid="
								+ wikiID;
						new ApiCall(context).execute("GET", url).get();
						msg = "Suggestion updated in wiki module...";
					} else {
						String url = "https://www.elearning.rwth-aachen.de/_vti_bin/l2pservices/api.svc/v1/addWiki?accessToken="
								+ token
								+ "&cid=14ss-38343&title="
								+ tView.getText().toString()
								+ "&body="
								+ cView.getText().toString();
						String output = new ApiCall(context)
								.execute("GET", url).get();
						JSONObject jsonObject = new JSONObject(output);
						editor.putString("wikiID",
								jsonObject.getString("itemId")).commit();
						msg = "Suggestion inserted in wiki module\u2026";
					}
					Toast.makeText(context, msg, Toast.LENGTH_LONG).show();
				} catch (Exception e) {
					Log.e("L2P Suggestion", e.getMessage());
				}

			}
		});
	}
}
